package com.sxt.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.sxt.dao.GoodsCategoryDao;
import com.sxt.domain.GoodsCategory;
import com.sxt.model.Menu;
import com.sxt.service.GoodsCatService;

@Service
@CacheConfig(cacheNames="com.sxt.GoodsCat")
public class GoodsCatServiceImpl implements GoodsCatService{

	@Autowired
	private GoodsCategoryDao dao;
	
	@Override
	public List<Menu> loadMenuByPId(Short id) {
		Assert.notNull(id, "加载子菜单时，父ID不能为空");
		List<GoodsCategory> goodsCategorys = dao.findByParentId(id);
		ArrayList<Menu> menus = new ArrayList<>();
		goodsCategorys.forEach((goodsCat)->{
			menus.add(new Menu(goodsCat.getId().intValue(), goodsCat.getName(), goodsCat.getLevel().equals((byte)3)?"open":"closed"));
		});
		return menus;
	}


	@Cacheable
	public List<Menu> loadAllMenu() {
		return loadAllMenu((short)0);
	}
	
	public List<Menu> loadAllMenu(Short pid){
		List<Menu> menus = new ArrayList<Menu>();
		List<GoodsCategory> firstMenu = dao.findByParentId(pid);
		for (GoodsCategory goodsCategory : firstMenu) {
			Menu menu = new Menu(goodsCategory.getId().intValue(), goodsCategory.getName(), null);
			menu.setChildren(loadAllMenu(goodsCategory.getId()));
		    menus.add(menu);
		}
		return menus;
	}

}
